import angular from 'angular';
import loadingTemplate from './ng-loading.template.html';

function LoadingProvider() {
  var defaults = {
    text: '',
    color: '#1890ff',
    size: 'medium' // small, medium, large
  };

  this.setDefaults = function setDefaults(options) {
    if (options) {
      angular.extend(defaults, options);
    }
  };

  this.$get = [
    '$rootScope',
    '$compile',
    '$timeout',
    '$document',
    function getLoading($rootScope, $compile, $timeout, $document) {
      var currentScope = null;
      var currentElement = null;

      function attachElement(element) {
        var body = $document.find('body');
        body.append(element);
      }

      function teardown(scope, element) {
        if (element) {
          element.remove();
        }
        if (scope) {
          scope.$destroy();
        }
      }

      return {
        show: function(options) {
          // 如果已经有 loading 显示，先隐藏
          if (currentElement) {
            this.hide();
          }

          var scope = $rootScope.$new();
          var config = angular.extend({}, defaults, options || {});

          scope.config = config;
          scope.visible = false;

          currentScope = scope;
          currentElement = $compile(loadingTemplate)(scope);

          attachElement(currentElement);

          // 延迟显示以触发动画
          $timeout(function show() {
            scope.visible = true;
          }, 10);
        },

        hide: function() {
          if (!currentElement || !currentScope) {
            return;
          }

          currentScope.visible = false;

          // 等待动画完成后移除元素
          $timeout(function() {
            teardown(currentScope, currentElement);
            currentScope = null;
            currentElement = null;
          }, 300);
        }
      };
    }
  ];
}

export default LoadingProvider;
